<template>
  <div class="module-container">
    <h2>{{ title }}</h2>
    <div class="module-content">
      <div class="search-container">
        <div class="search-box">
          <input 
            type="text" 
            v-model="searchQuery" 
            :placeholder="searchPlaceholder"
            class="search-input"
          />
          <button @click="handleSearch" class="search-button">搜索</button>
          <button 
            v-if="showCreateButton" 
            @click="handleCreate" 
            class="create-button"
          >
            {{ createButtonText }}
          </button>
          <button 
            v-if="showBatchDeleteButton"
            @click="handleBatchDelete"
            class="batch-delete-button"
            :disabled="selectedItems.length === 0"
          >
            批量删除<span v-if="selectedItems.length > 0"> ({{ selectedItems.length }})</span>
          </button>
        </div>
        <!-- 高级搜索插槽 -->
        <slot name="advanced-search"></slot>
      </div>
      
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th v-if="showSelection">
                <input 
                  type="checkbox" 
                  :checked="areAllItemsSelected" 
                  @change="toggleSelectAll"
                />
              </th>
              <th v-for="column in columns" :key="column.key">{{ column.title }}</th>
              <th v-if="showActions">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in data" :key="item[keyField] || index">
              <td v-if="showSelection">
                <input 
                  type="checkbox" 
                  :checked="selectedItems.includes(item[keyField])"
                  @change="() => toggleItemSelection(item[keyField])"
                />
              </td>
              <td v-for="column in columns" :key="column.key">
                <slot 
                  :name="'column-' + column.key" 
                  :item="item" 
                  :value="item[column.key]"
                >
                  {{ formatValue(item[column.key], column.format) }}
                </slot>
              </td>
              <td v-if="showActions">
                <button 
                  v-for="action in actions" 
                  :key="action.name"
                  :class="['action-button', action.type || 'default']"
                  @click="handleAction(action.name, item)"
                >
                  {{ action.label }}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <div class="pagination">
        <button 
          class="pagination-button" 
          :disabled="currentPage <= 1"
          @click="prevPage"
        >
          上一页
        </button>
        <span class="pagination-info">第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
        <button 
          class="pagination-button" 
          :disabled="currentPage >= totalPages"
          @click="nextPage"
        >
          下一页
        </button>
      </div>
    </div>
    
    <!-- 批量删除确认对话框 -->
    <div v-if="showBatchDeleteDialog" class="dialog-overlay">
      <div class="dialog">
        <div class="dialog-header">
          <h3>确认批量删除</h3>
        </div>
        <div class="dialog-body">
          <p v-if="selectedItems.length > 0">确定要删除选中的 {{ selectedItems.length }} 条记录吗？</p>
          <p v-else>请先选择要删除的记录</p>
        </div>
        <div class="dialog-footer">
          <button @click="cancelBatchDelete" class="cancel-button">取消</button>
          <button 
            v-if="selectedItems.length > 0"
            @click="confirmBatchDelete" 
            class="confirm-button danger"
          >
            确认删除
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'InfoTable',
  props: {
    title: {
      type: String,
      required: true
    },
    data: {
      type: Array,
      default: () => []
    },
    columns: {
      type: Array,
      required: true
    },
    keyField: {
      type: String,
      default: 'id'
    },
    showActions: {
      type: Boolean,
      default: true
    },
    actions: {
      type: Array,
      default: () => [
        { name: 'view', label: '查看', type: 'view' },
        { name: 'edit', label: '编辑', type: 'edit' },
        { name: 'delete', label: '删除', type: 'delete' }
      ]
    },
    showCreateButton: {
      type: Boolean,
      default: true
    },
    showBatchDeleteButton: {
      type: Boolean,
      default: true
    },
    showSelection: {
      type: Boolean,
      default: true
    },
    selectedItems: {
      type: Array,
      default: () => []
    },
    createButtonText: {
      type: String,
      default: '创建'
    },
    searchPlaceholder: {
      type: String,
      default: '请输入搜索内容'
    },
    pagination: {
      type: Object,
      default: () => ({
        current: 1,
        pageSize: 10,
        total: 0
      })
    }
  },
  data() {
    return {
      searchQuery: '',
      currentPage: this.pagination.current || 1,
      showBatchDeleteDialog: false
    }
  },
  computed: {
    totalPages() {
      return Math.ceil((this.pagination.total || 0) / (this.pagination.pageSize || 10));
    },
    // 检查是否所有项目都被选中
    areAllItemsSelected() {
      return this.data.length > 0 && 
             this.selectedItems.length === this.data.length;
    }
  },
  methods: {
    formatValue(value, format) {
      if (!format) return value;
      
      switch (format) {
        case 'date':
          return value ? new Date(value).toLocaleDateString() : '-';
        case 'datetime':
          return value ? new Date(value).toLocaleString() : '-';
        case 'currency':
          return value ? `¥${value}` : '¥0';
        case 'boolean':
          return value ? '是' : '否';
        case 'status':
          // 支持数字和字符串状态值
          return value === 1 || value === '1' || value === 'active' || value === '正常' ? '正常' : '停用';
        default:
          return value;
      }
    },
    handleSearch() {
      this.$emit('search', this.searchQuery);
    },
    handleCreate() {
      this.$emit('create');
    },
    handleAction(actionName, item) {
      this.$emit('action', { action: actionName, item });
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.$emit('page-change', this.currentPage);
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.$emit('page-change', this.currentPage);
      }
    },
    // 切换项目选择状态
    toggleItemSelection(itemId) {
      this.$emit('toggle-item-selection', itemId);
    },
    // 切换全选状态
    toggleSelectAll(event) {
      this.$emit('toggle-select-all');
    },
    // 处理批量删除
    handleBatchDelete() {
      this.showBatchDeleteDialog = true;
    },
    // 确认批量删除
    confirmBatchDelete() {
      this.$emit('batch-delete', this.selectedItems);
      this.showBatchDeleteDialog = false;
    },
    // 取消批量删除
    cancelBatchDelete() {
      this.showBatchDeleteDialog = false;
    },
    // 清除选中项
    clearSelection() {
      this.$emit('clear-selection');
    }
  },
  watch: {
    'pagination.current'(newVal) {
      this.currentPage = newVal;
      // 页面变化时清除选中项
      this.clearSelection();
    },
    data() {
      // 数据变化时清除选中项
      this.clearSelection();
    }
  }
}
</script>

<style scoped>
@import '../assets/global-module-styles.css';

.search-box {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.create-button {
  padding: 10px 20px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  align-self: center;
  white-space: nowrap;
}

.create-button:hover {
  background-color: #218838;
}

.batch-delete-button {
  padding: 10px 20px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  align-self: center;
  white-space: nowrap;
}

.batch-delete-button:hover {
  background-color: #c82333;
}

.batch-delete-button:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.action-button.delete {
  background-color: #dc3545;
  color: white;
}

.action-button.view {
  background-color: #17a2b8;
  color: white;
}

.action-button.edit {
  background-color: #ffc107;
  color: #212529;
}

.pagination-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 4px;
  min-width: 300px;
  max-width: 500px;
}

.dialog-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  margin: 0;
  color: #333;
}

.dialog-body {
  padding: 20px;
}

.dialog-body p {
  margin: 0;
  color: #666;
}

.dialog-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-button {
  padding: 8px 16px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-button:hover {
  background-color: #5a6268;
}

.confirm-button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-button.danger {
  background-color: #dc3545;
  color: white;
}

.confirm-button.danger:hover {
  background-color: #c82333;
}
</style>